<template>
  <base-modal
    :show.sync="visible"
    width="420px"
    class="edit-dialog"
    @closed="onClose('form')"
  >
    <div slot="title">
      <span class="el-dialog__title">{{
        form.id ? $t('customer.setting.editCardnameDialog.title1') : $t('customer.setting.editCardnameDialog.title2')
      }}</span>
    </div>
    <div class="base-modal-content">
      <el-form :model="form" :rules="rules" ref="form" label-position="top">
        <el-form-item class="form-item-language" :label="$t('customer.setting.editCardnameDialog.label1')" prop="name">
          <el-input
            :value="form.name"
            :placeholder="$t('customer.setting.editCardnameDialog.pla1')"
            maxlength="20"
            @input="nameInput"
          ></el-input>
          <!-- 选择语言 -->
          <base-select-language 
            v-if="isConnectorAddOnCard"
            :field="{
              fieldName: 'titleLanguage',
              formType:'text',
            }"
            :defaultOption="{
              formType:'text',
            }"
            defaultFormType="text"
            :defaultValue="titleValue"
            :defaultValueLanguage="form.titleLanguage || {[currentLanguage]: form.name}"
            @save="(e) => languageSave('titleLanguage', 'name', e)"
          >
          </base-select-language>
        </el-form-item>
        <el-form-item class="form-item-language" :label="$t('customer.setting.editCardnameDialog.label2')" prop="description">
          <el-input
            type="textarea"
            :value="form.description"
            :placeholder="$t('customer.setting.editCardnameDialog.pla2')"
            maxlength="120"
            @input="descriptionInput"
          ></el-input>
          <!-- 选择语言 -->
          <base-select-language 
            v-if="isConnectorAddOnCard"
            :field="{
              fieldName: 'descLanguage',
              formType:'textarea',
            }"
            :defaultOption="{
              formType:'textarea',
            }"
            defaultFormType="textarea"
            :defaultValue="descValue"
            :defaultValueLanguage="form.descLanguage || {[currentLanguage]: form.description}"
            @save="(e) => languageSave('descLanguage', 'description', e)"
          >
          </base-select-language>
        </el-form-item>
        <el-form-item prop="resource">
          <div slot="label">
            {{$t('customer.setting.editCardnameDialog.label3')}}
            <el-tooltip
              effect="dark"
              :content="content"
              placement="top"
            >
              <span><i class="el-icon-question"></i>：</span>
            </el-tooltip>
          </div>
          <el-radio-group v-model="form.inputType" :disabled="form.id?true:false">
            <el-radio label="single">{{$t('common.base.onceTime')}}</el-radio>
            <el-radio label="multiple">{{$t('common.base.moreTime')}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="onClose('form')">{{$t('common.base.cancel')}}</el-button>
      <el-button type="primary" @click="onSubmit('form')" v-if="form.id"
      >{{$t('common.base.confirm')}}</el-button
      >
      <el-button type="primary" @click="onSubmit('form')" v-else
      >{{$t('common.base.nextStep')}}</el-button
      >
    </div>
  </base-modal>
</template>

<script>
import * as SettingCusProApi from '@src/api/SettingCusProApi';
import { getConnectorName, updateConnectorName } from '@src/modules/connector/api';
import { openAccurateTab } from '@src/util/platform'
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import i18n from '@src/locales'

/* service */
import { isConnectorCard } from '@service/CardService';

export default {
  name:'edit-cuspro-name-dialog',
  data(){
    return{
      visible: false,
      form: {
        id: '',
        name: '',
        description: '',
        inputType: 'single',
        titleLanguage: {},
        descLanguage: {}
      },
      rules: {
        name: [{ required: true, message: i18n.t('common.placeholder.inputName'), trigger: 'blur' }],
      },
    }
  },
  props:{
    card:{
      type: Object,
      default:()=>null
    },
    cardType:String
  },
  computed:{
    content(){
      return i18n.t('customer.setting.editCardnameDialog.des1', {data1: this.cardType==='customer'? i18n.t('common.form.type.customer') : i18n.t('common.form.type.product')})
    },
    currentLanguage() {
      return i18n.locale;
    },
    titleValue() {
      return this.form?.titleLanguage?.[this.currentLanguage] || this.form.name;
    },
    descValue() {
      return this.form?.descLanguage?.[this.currentLanguage] || this.form.description;
    },
    /** 
     * 是否是连接器附加组件
     * @description
    */
    isConnectorAddOnCard(){
      return isConnectorCard(this.card)
    }
  },
  methods: {
    // 获取连接器名称描述
    async fetchConnectorName() {
      try {
        const res = await getConnectorName(this.card?.config?.connectorInfo);
        if(res.status == 0){ 
          const { data = {} } = res
          
          this.form.id = data.id
          this.form.name = data.connectorName || ''
          this.form.description = data.connectorRemarks || ''
          this.form.titleLanguage = data.titleLanguage || ''
          this.form.descLanguage = data.descLanguage || {}
        } else {
          this.$message.error(res.message);
        }
      } catch(e) {
        console.log('fetchConnectorName => ', e)
      }
    },
    async openDialog() {
      try {
        if(this.card){
          this.form = Object.assign(this.form, this.card);
        }

        // 是连接器 并且 是编辑 
        if (this.isConnectorAddOnCard && this.form?.id) {
          this.fetchConnectorName()
        }
      }catch(e) {
        console.log(e)
      }

      this.visible = true;
    },
    onClose(form) {
      this.visible = false;
      this.$refs[form].resetFields();
    },
    onSubmit(form){
      this.$refs[form].validate((valid) => {
        if(valid){
          if(this.form.id){
            // 修改组件
            if(this.isConnectorAddOnCard) {
              this.onDialogConfirmHandler(form);
            }else {
              this.onUpdateCardReq(form);
            }
          }else{
            // 新建组件
            this.onCreatCardReq();
          }
        }else{
          console.log('error submit!!');
          return false;
        }
      })
    },
    // 连接器编辑接口
    onDialogConfirmHandler(form){
      
      const params = {
        id: this.form.id,
        connectorName: this.form.name,
        connectorRemarks: this.form.description,
        titleLanguage: this.form.titleLanguage,
        descLanguage: this.form.descLanguage
      }
      updateConnectorName(params).then(res=>{
        if(res.status == 0){
          this.$message.success(this.$t('common.base.tip.editSuccess'));
          this.$emit('editCardSubmit');
          this.onClose(form);
        }else{
          this.$message.error(res.message);
        }
      })
    },
    // 新建组件
    async onCreatCardReq(){
      try{
        const name=this.form.name;
        const params={
          description: this.htmlEscape(this.form.description),
          name,
          inputType:this.form.inputType,
          cardType:this.cardType,
          titleLanguage: this.form.titleLanguage || {[this.currentLanguage]: this.form.name},
          descLanguage: this.form.titleLanguage || {[this.currentLanguage]: this.form.description}
        }
        let {result,code,message}=await SettingCusProApi.cardSave(params);
        if(code===0){
          this.$message.success(this.$t('common.base.tip.createSuccess'));

          let currentTabId =''
          if (window.frameElement) {
          	currentTabId = window.frameElement.dataset.id;
          }
          setTimeout(()=>{
            let cardId = result;
            this.onClose('form')
            // this.$platform.openTab({
            //   id: 'customer_card_setting',
            //   title: '附加组件表单设置',
            //   url: `/setting/customer/cardFormfields?id=${cardId}&name=${encodeURIComponent(name)}&cardType=${this.cardType}&prevTabId=${currentTabId}`,
            //   reload: true,
            // });
            openAccurateTab({
              type: PageRoutesTypeEnum.PageCustomerAdditionalFormSet,
              params: `id=${cardId}&name=${encodeURIComponent(name)}&cardType=${this.cardType}&prevTabId=${currentTabId}`,
              reload: true,
            })
          }, 1000)
        }else{
          this.$message.error(message);
        }
      }catch(err){
        console.error(err);
      }
    },
    // 修改组件
    async onUpdateCardReq(form){
      try{
        const params = {
          description: this.htmlEscape(this.form.description),
          id: this.form.id,
          name: this.form.name,
          cardType:this.cardType,
          titleLanguage: this.form.titleLanguage || {[this.currentLanguage]: this.form.name},
          descLanguage: this.form?.descLanguage || {[this.currentLanguage]: this.form?.description}
        }
        let {code,message}=await SettingCusProApi.cardSave(params);
        if(code===0){
          this.$message.success(this.$t('common.base.tip.editSuccess'));
          this.$emit('editCardSubmit');
          this.onClose(form);
        }else{
          this.$message.error(message);
        }
      }catch(err){
        console.error(err);
      }
    },
    languageSave(fieldName, modelName, data) {
      if(this.form[fieldName] !== data[i18n.locale]){
        this.$set(this.form, modelName, data[i18n.locale]);
      }
      this.$set(this.form, fieldName, data);
    },
    nameInput(e) {
      this.form.name = e;
      this.$set(this.form.titleLanguage, i18n.locale, e);
    },
    descriptionInput(e) {
      this.form.description = e;
      this.$set(this.form.descLanguage, i18n.locale, e);
    },
    // 防止XSS的恶意脚本攻击
    htmlEscape(value){
      return value.replace(/</g, '&lt;').replace(/>/g, '&gt;');
    },
  }
}
</script>

<style lang="scss">
.edit-dialog {
  .base-modal-header {
    display: flex;
    justify-content: space-between;
    .el-dialog__title {
      font-size: 18px;
    }
    .el-tooltip {
      color: #999;
    }
  }
  .base-modal-body {
    padding: 20px;
    .el-form {
      .el-form-item {
        .el-form-item__content {
          width: 280px;
          .el-radio {
            margin-right: 24px;
          }
        }
        .el-tooltip {
            color: #999;
        }
      }
    }
  }

  .base-modal-content {
    .form-item-language {
      .el-form-item__content {
        display: flex;
        flex-wrap: wrap;

        >div:nth-child(1) {
          flex: 1;
        }

        .language {
          width: 32px;
        }

        .err-msg-wrap {
          width: 100%;
        }
      }
    }
  }
}
</style>